M.yuqueDocApi="https://www.yuque.com/api/v2/repos/vdbwag/dl4xgu/docs/arl0yw?raw=1";
M.token="ZW9aH3CUDFWvC0ZU6nzoozBg03smn6Y5D36LqB8x"
M.reqComHeaders={"X-Auth-Token": M.token,"User-Agent":"PostmanRuntime/7.26.1"}

if(!M.yuqueServerObj){
    M.yuqueServerObj={"/test":"{}"}
}
 function registYuqueServer(){
    return  new Promise((resolve, reject) => {
            M.get(M.yuqueDocApi).then(s=>{   
                  s=s.data.body;
                  s=s.replace(/\<br.*/g,"")
                  let s1=s.split(/\`\`\`/g)
                  let resultArr=[]
                  for(let i=0;i<s1.length;i++){
                  if(i>0 && s1[i].startsWith("json\n") && s1[i-1].endsWith("responseBody\n")){
                        resultArr.push(s1[i].replace("json\n",""))
                  }
                  
                  }
                  resultArr=resultArr.map(u=>u.replace(/\/\/(.+)+/g,""))
                  //console.log(resultArr[0])
                  let text=s;
                  text = text.replace(/"|'|`/g, "");
                  text = text.replace(/ +/g, " ");
                  let arr = text.split(/[\r\n]/g);
                  let pathList=[]
                  for(let i=0;i<arr.length;i++){
                    if(arr[i].trim().startsWith("GET ") || arr[i].trim().startsWith("POST ")){
                          if(arr[i].trim().startsWith("GET ")){
                              pathList.push("get@"+arr[i].replace(/GET|POST/g,"").trim());
                          }else{
                              pathList.push("post@"+arr[i].replace(/GET|POST/g,"").trim());
                          }
                    }
                    }
                    for(let i=0;i<arr.length;i++){
                        if(pathList[i]){
                             // console.log(pathList[i],"QQ")
                              let mpath=pathList[i].split("@")
                             // console.log(mpath,"mpath")
                              try{
                                  try{
                                       JSON.parse(resultArr[i])
                                       app[mpath[0]](mpath[1],(req,res)=>{res.send(resultArr[i])})
                                  }catch(e){
                                      app[mpath[0]](mpath[1],eval(resultArr[i]))
                                  }
                              }catch(e1){
                                  continue;
                                  console.error(e1);
                              }
                              M.yuqueServerObj[pathList[i]]=resultArr[i];
                        }}
                  resolve(M.yuqueServerObj)  
      })
  })
}

registYuqueServer().then(u=>console.log(u))



app.begin((req, res) => {
      console.log("req ", req.url)
      var pathname = url_module.parse(req.url).pathname;
      if (Object.keys(M.yuqueServerObj).indexOf(pathname)>-1) {
          res.send(M.yuqueServerObj[pathname])
      }
  })